package cz.spock.core.util;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * filter for ajax login
 * 
 * @author miso
 *
 */
// TODO test
public class SecurityAjaxFilter extends OncePerRequestFilter {

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!isAjaxRequest(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        RedirectResponseWrapper redirectResponseWrapper = new RedirectResponseWrapper(response);

        filterChain.doFilter(request, redirectResponseWrapper);

        if (redirectResponseWrapper.getRedirect() != null) {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain;charset=utf-8");

            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Pragma", "no-cache");

            String redirectURL = redirectResponseWrapper.getRedirect();
            String json;
            if (redirectURL.indexOf("authfailed=true") == -1) {
                json = "{\"result\":true, \"data\":{\"url\":\"" + redirectURL + "\"}}";
            } else {
                String error = ((AuthenticationException) request.getSession().getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)).getMessage();
                json = "{\"result\":false, \"data\":{\"message\":\"" + error + "\"}}";
            }
            response.getOutputStream().print(json);
            response.getOutputStream().close();
        }
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        System.out.println("is ajax request?");
        String isAjax = request.getParameter("ajax");
        if (isAjax == null)
            return false;
        return (request.getParameter("ajax")).equals("true");
    }

}
